# -*- coding: utf-8 -*-

import os
import sys
import datetime
import pytz
import jinja2

from openerp import SUPERUSER_ID, models
from openerp.osv import fields
from openerp.osv import orm
from openerp.osv import osv
from openerp.http import request

if hasattr(sys, 'frozen'):
    # When running on compiled windows binary, we don't have access to package
    # loader.
    path = os.path.realpath(os.path.join(
        os.path.dirname(__file__), '..', 'views'))
    loader = jinja2.FileSystemLoader(path)
else:
    loader = jinja2.PackageLoader('openerp.addons.dftg_lodop', "report")

env = jinja2.Environment(loader=loader, autoescape=True)

class CursorProxy():
    def __init__(self):
        pass

    def dictfetchone(self, *args):
        request.cr.execute(*args)
        return request.cr.dictfetchone()

    def dictfetchall(self, *args):
        request.cr.execute(*args)
        return request.cr.dictfetchall()


# jinja2 自定义对象
env.globals['_cr'] = CursorProxy()

# jinja2模版自定义过滤器
def strftime(str, fmt):
    dt = datetime.datetime.strptime(str, '%Y-%m-%d %H:%M:%S')
    dt = dt.replace(tzinfo=pytz.utc).astimezone(pytz.timezone('Asia/Shanghai'))
    return dt.strftime(fmt.encode('utf-8')).decode('utf-8')

env.filters['strftime'] = strftime



# 销售订单打印扩展，调用lodop打印
class sale_order_lodop(osv.osv):
    _name = 'sale.order'
    _inherit = 'sale.order'

    def print_quotation(self, cr, uid, ids, context=None):
        '''
        This function prints the sales order and mark it as sent, so that we can see more easily the next step of the workflow
        '''
        assert len(
            ids) == 1, 'This option should only be used for a single id at a time'
        order = self.browse(cr, uid, ids, context=context)
        # if order.state == "progress":
        #    self.signal_workflow(cr, uid, ids, 'order_print')
        # else:
        #    self.signal_workflow(cr, uid, ids, 'quotation_sent')
        # 会调用下面的sale_order_lodop_report方法(report/models/report.py
        # 156行特殊报表:particularreport_obj，是关键)
        return self.pool['report'].get_action(cr, uid, ids, 'sale_order_lodop', context=context)
# 销售订单打印扩展，调用lodop打印


class res_users_lodop(osv.osv):
    _name = 'res.users'
    _inherit = 'res.users'

    def print_quotation(self, cr, uid, ids, context=None):
        '''
        This function prints the sales order and mark it as sent, so that we can see more easily the next step of the workflow
        '''
        assert len(
            ids) == 1, 'This option should only be used for a single id at a time'
        order = self.browse(cr, uid, ids, context=context)
        # if order.state == "progress":
        #    self.signal_workflow(cr, uid, ids, 'order_print')
        # else:
        #    self.signal_workflow(cr, uid, ids, 'quotation_sent')
        # 会调用下面的sale_order_lodop_report方法(report/models/report.py
        # 156行特殊报表:particularreport_obj，是关键)
        return self.pool['report'].get_action(cr, uid, ids, 'report_res_users_lodop', context=context)

#邮寄ems类型的打印
class report_res_users_lodop(osv.AbstractModel):
    """Model used to embed old style reports"""
    _name = 'report.report_res_users_lodop'
    _template = None
    _wrapped_report_class = None

    def render_html(self, cr, uid, ids, data=None, context=None):
        model = self.pool.get('res.users')
        template = env.get_template("customer_envelop_print.html")
        customers = []
        grades = {
            u'中断客户': 'ZD',
            u'跟进客户': 'GJ',
            u'潜力客户': 'QL',
            u'定样客户': 'DY',
            u'正式客户': 'ZS',
            u'重要客户': 'ZY',
            u'VIP客户': 'VIP,'
        }
        cr.execute("SELECT id, county_name FROM all_county WHERE city_id=3")
        county_rows = cr.dictfetchall()
        counties = {None: ''}
        for county in county_rows:
            counties.update({county.get('id'): county.get('county_name')})
        if ids:
            ids_string = str(ids)[1:-1]
            cr.execute("SELECT rp.id, rp.name, rp.cust_grade, ru.login AS op_name, rp.main_contacts, rp.principal"
                       " FROM res_partner rp INNER JOIN res_users ru ON rp.user_id=ru.id"
                       " WHERE rp.user_id in (%s) AND rp.active=True AND rp.customer=True"
                       " ORDER BY rp.user_id, rp.share_to_uid, rp.cust_grade DESC, rp.last_contact_date DESC"
                       % str(ids_string))
            customers = cr.dictfetchall()
        return template.render({
            'customers': customers,
            'grades': grades,
            'counties': counties,
            'subscription_type': u'邮政'
        })

# 邮寄ems类型的打印
class report_res_users_crm_lead_lodop(osv.AbstractModel):
    """Model used to embed old style reports"""
    _name = 'report.report_res_users_crm_lead_lodop'
    _template = None
    _wrapped_report_class = None

    def render_html(self, cr, uid, ids, data=None, context=None):
        lead_obj = self.pool.get('crm.lead')
        template = env.get_template("report_crm_lead_contacts.html")
        all_customer = {}
        for id in ids:
            customers = lead_obj.search_read(cr, uid, [('user_id', '=', id), ('is_subscription', '=', True),
                                                          ('county_id', '!=', False), ('street', '!=', False)],
                                                         ['partner_name', 'contact_name', 'county_id', 'street',
                                                          'zip', 'user_id', 'department'], context=context)
            for customer in customers:
               customer.update({
                    'address': '%s%s' % (customer.get('county_id', [False, False])[1], customer.get('street')),
                    'op_name': customer.get('user_id', [False, False])[1],
                    'linkname': customer.get('contact_name'),
                    'name': customer.get('partner_name')})

            if customers:
                all_customer.update({customers[0].get('op_name'): customers})
        return template.render({
            'all_customer': all_customer,
            'subscription_type': u'邮政'
        })

#邮寄快递类型的打印
class report_res_users_lodop_express(osv.AbstractModel):
    """Model used to embed old style reports"""
    _name = 'report.report_res_users_lodop_express'
    _template = None
    _wrapped_report_class = None

    def render_html(self, cr, uid, ids, data=None, context=None):
        model = self.pool.get('res.users')
        template = env.get_template("customer_envelop_export_csv.html")
        customers = []
        grades = {
            u'中断客户': 'ZD',
            u'跟进客户': 'GJ',
            u'潜力客户': 'QL',
            u'定样客户': 'DY',
            u'正式客户': 'ZS',
            u'重要客户': 'ZY',
            u'VIP客户': 'VIP,'
        }
        cr.execute("SELECT id, name FROM res_country_state WHERE country_id=49")
        province_rows = cr.dictfetchall()
        provinces = {None: ''}
        for province in province_rows:
            provinces.update({province.get('id'): province.get('name')})

        cr.execute("SELECT id, city_name FROM all_city")
        city_rows = cr.dictfetchall()
        cities = {None: ''}
        for city in city_rows:
            cities.update({city.get('id'): city.get('city_name')})

        cr.execute("SELECT id, county_name FROM all_county")
        county_rows = cr.dictfetchall()
        counties = {None: ''}
        for county in county_rows:
            counties.update({county.get('id'): county.get('county_name')})
        if ids:
            ids_string = str(ids)[1:-1]
            cr.execute("""SELECT rp.id, rp.name, rp.cust_grade,
          ru.login AS op_name,
          op_partner.mobile as op_mobile,
          rp.main_contacts, rp.principal FROM res_partner rp
    INNER JOIN res_users ru ON rp.user_id=ru.id
    INNER JOIN res_partner op_partner ON op_partner.id=ru.partner_id
    WHERE rp.user_id in (%s) AND rp.active=True AND rp.customer=True
    ORDER BY rp.user_id, rp.cust_grade DESC, rp.share_to_uid, rp.last_contact_date DESC""" % ids_string)
            customers = cr.dictfetchall()
        return template.render({
            'customers': customers,
            'grades': grades,
            'provinces': provinces,
            'cities': cities,
            'counties': counties,
            'subscription_type': u'快递'
        })

# render订单打印模板


class report_sale_order_lodop(osv.AbstractModel):
    """Model used to embed old style reports"""
    _name = 'report.sale_order_lodop'
    _template = None
    _wrapped_report_class = None

    def render_html(self, cr, uid, ids, data=None, context=None):
        model = 'sale.order'
        report_obj = self.pool[model]
        order = report_obj.browse(cr, uid, ids, context=context)
        # 如果订单不是草稿状态或待审核状态打印，则将打印状态修改为已打印
        if order.state not in ['draft', 'sent']:
            order.write({'print_state': True})

        category_ids = order.partner_id.category_id
        is_vip = False
        for category_id in category_ids:
            if category_id.name == u'大客户':
                is_vip = True

        #取得外部开票发票信息
        official_invoice_outer_line = {} #{False: 1L, True: 1L}
        if order.sale_order_invoice:
            cr.execute("SELECT * FROM official_invoice_lines WHERE official_invoice_id=%s AND is_outer_invoice=TRUE", (order.sale_order_invoice.id, ))
            official_invoice_outer_line = cr.dictfetchall()
        #备注分行
        note_lines = []
        if order.note:
            note_lines = order.note.split('\n')
        options = data or {}
        template = env.get_template("sale_order_print.html")
        chinese = {'0': '零', '1': '壹', '2': '贰', '3': '叁', '4': '肆',
                   '5': '伍', '6': '陆', '7': '柒', '8': '捌', '9': '玖'}
        cr.execute("SELECT login FROM res_users WHERE id=%s", (order.user_id.id,))
        user_id_name = cr.fetchone()[0]

        url_prefix = "http://" + request.httprequest.host
        #暂时切换到大厅打印服务器
        lodop_host = '192.168.0.10'
        if url_prefix.find('localhost') > 0 or url_prefix.find('tunnel') > 0:
            lodop_host = '127.0.0.1'

        return template.render({
            'order': order,
            'user_id_name': user_id_name,
            'note_lines': note_lines,
            'debug': context,
            'options': options,
            'chinese': chinese,
            'official_invoice_outer_line': official_invoice_outer_line,
            'is_vip': is_vip,
            'url_prefix': url_prefix,
            'lodop_host': lodop_host
        })
        # return self.pool['report'].render(cr, uid, [], self._template,
        # docargs, context=context)

# render出货单打印模板
# class report_stock_picking_lodop(osv.AbstractModel):
#     """Model used to embed lodop reports"""
#     _name = 'report.stock_report_picking_ext'
#     _template = None
#     _wrapped_report_class = None

#     def render_html(self, cr, uid, ids, data=None, context=None):
#         model = 'stock.picking'
#         report_obj = self.pool[model]
#         picking = report_obj.browse(cr, uid, ids, context=context)

#         #先取到出货单对应的订单id，再去取得订单的对象
#         order_id = self.pool.get('sale.order').search(cr, uid, [('name','=',picking.origin)])
#         order = self.pool.get('sale.order').browse(cr, uid, order_id, context=None)
#         curUser = self.pool.get('res.users').browse(cr,uid,uid,context=None)
#         template = env.get_template("stock_picking_print.html")
#         return template.render({
#             'picking': picking,
#             'order': order,
#             'curUser': curUser,
#             'debug': context,
#             })
